
import { ref, computed } from 'vue'
import { useDeviceTreeStore } from '@/store/modules/deviceTreeStore'

/**
 * 设备相关工具函数 Hook
 */
export function useDeviceUtils() {
  const deviceTreeStore = useDeviceTreeStore()

  // 设备名称缓存
  const deviceNameCache = ref(new Map<string, string>())

  /**
   * 根据设备编码获取设备名称
   */
  const getDeviceNameByCode = (deviceCode: string): string => {
    console.log("设备编码:", deviceTreeStore.currentTreeNode)

    if (!deviceCode) return ''

    // 检查缓存
    if (deviceNameCache.value.has(deviceCode)) {
      return deviceNameCache.value.get(deviceCode)!
    }

    // 递归查找设备节点
    const findNode = (nodes: any[], code: string): any => {
      if (!nodes || !Array.isArray(nodes)) return null

      for (const node of nodes) {
        if (node.deviceCode === code) {
          return node
        }
        if (node.children && Array.isArray(node.children)) {
          const found = findNode(node.children, code)
          if (found) return found
        }
      }
      return null
    }

    // 从设备树中查找（包括整个树结构，不只是当前节点）
    let deviceNode = null

    // 先在整个设备树中查找
    if (deviceTreeStore.currentTreeNode ) {
      deviceNode = findNode([deviceTreeStore.currentTreeNode], deviceCode)
    }

    // 如果没找到，尝试在当前节点及其子节点中查找
    if (!deviceNode && deviceTreeStore.currentTreeNode) {
      deviceNode = findNode([deviceTreeStore.currentTreeNode], deviceCode)
    }

    const deviceName = deviceNode?.deviceName || '未知设备'

    // 存入缓存
    deviceNameCache.value.set(deviceCode, deviceName)
    return deviceName
  }

  /**
   * 清空设备名称缓存
   */
  const clearDeviceNameCache = () => {
    deviceNameCache.value.clear()
  }

  /**
   * 批量获取设备名称
   */
  const getDeviceNamesByCodes = (deviceCodes: string[]): Record<string, string> => {
    const result: Record<string, string> = {}
    deviceCodes.forEach(code => {
      result[code] = getDeviceNameByCode(code)
    })
    return result
  }

  return {
    getDeviceNameByCode,
    getDeviceNamesByCodes,
    clearDeviceNameCache
  }
}
